//
//  AppDelegate.m
//  wanzhaoIM
//
//  Created by liuyuantao on 15/4/7.
//  Copyright (c) 2015年 liuyuantao. All rights reserved.
//

#import "AppDelegate.h"
#import "MicroDef.h"
#import "LoginViewController.h"
#import "DDLog.h"
#import "DDTTYLogger.h"
#import "XMPPLogging.h"
#import "DDFileLogger.h"
#import "GesturePasswordController.h"
#import "UIUtil.h"
#import "PersonalVersion.h"
#import "CommonVersion.h"
#import "CCurrentAccountMgr.h"
#import "UMessage.h"
#import "AFNetworking.h"
#import "CFolderMgr.h"
#import "CXmppMgr.h"
#import "CUserSettingMgr.h"
#import "CUserSettingModel.h"
#import "NewFeatureController.h"
#import "CXmppRequestMgr.h"
#import "JKAlertDialog.h"
#import "CMessageMgr.h"
#import "WZNavigationController.h"
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import "EFRootViewController.h"
#import "EFengAndEtongRootController.h"
#import "WZRootViewController.h"
#import <Bugly/Bugly.h>
#import "FaceppAPI.h"
#import "FaceCertifyViewController.h"
#import "sys/utsname.h"
#import "WXApi.h"
#import "inMoneyViewController.h"
#define BUGLY_APP_ID @"900030990"
#import "AppDelegate+LocalNotification.h"
#import "EFengComposeController.h"
#import "WZMobileSignController.h"
@interface AppDelegate ()<WXApiDelegate>

{
    NSOperationQueue *_queen;
    
}

@property (nonatomic, strong) BMKMapManager* mapManager;
@property (nonatomic,assign) NSTimeInterval lasttime;
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    sleep(2);
    [USER_DEFAULT setBool:YES forKey:@"sendOK"];
    [USER_DEFAULT synchronize];
    CGFloat fontSize = [USER_DEFAULT floatForKey:@"messageFontSize"];
    if (fontSize == 0) {
        [USER_DEFAULT setFloat:16 forKey:@"messageFontSize"];
        [USER_DEFAULT synchronize];
    }
    if ([self getCurrentDevice] > 7) {
         [self configShortCutItems];
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(forceQuit:) name:K_XMPPDIDFORCEQUIT object:nil];
    CommonVersion *versionUpdate = [[CommonVersion alloc] init];
    [versionUpdate updateDBVersions];
    [CXmppMgr shareInstance];
    [WXApi registerApp:WXAPPID withDescription:@"e蜂"];
    [Bugly startWithAppId:BUGLY_APP_ID];
    
    [UMessage startWithAppkey:KUMENGKEY launchOptions:launchOptions];
    [self registerRemoteNotification];
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED <= __IPHONE_6_1
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
#else
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
#endif
    DDFileLogger *fileLogger = [[DDFileLogger alloc] init];
    [DDLog addLogger:fileLogger];
    [DDLog addLogger:[DDTTYLogger sharedInstance] withLogLevel:ddLogLevel];
    
    // Override point for customization after application launch.
    CGRect mainScreen = [[UIScreen mainScreen] bounds];
    self.window = [[UIWindow alloc] initWithFrame:mainScreen];
    self.window.backgroundColor = [UIColor whiteColor];
    BOOL isForceQuit = [USER_DEFAULT boolForKey:ISFORCEQUIT];
    
    //判断是否是第一次使用
    NSString *key = (__bridge_transfer NSString *)kCFBundleVersionKey;
    NSDictionary *dict = [NSBundle mainBundle].infoDictionary;
    NSString *currentVersion = dict[key];
    
    NSUserDefaults *defaults = USER_DEFAULT;
    NSString *sandBoxVersion = [defaults valueForKey:APP_VERSION];
    if ([currentVersion compare:sandBoxVersion] == NSOrderedDescending) {
        [defaults setObject:currentVersion forKey:APP_VERSION];
        [defaults synchronize];
        application.statusBarHidden = YES;
        self.window.rootViewController = [[NewFeatureController alloc] init];
    } else{
        CAccountModel *currentAcc = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
        LoginViewController *login = [[LoginViewController alloc] init];
        WZNavigationController *nav = [[WZNavigationController alloc] initWithRootViewController:login];
        nav.navigationBarHidden = YES;
        self.window.rootViewController = nav;
        if(currentAcc != nil && !isForceQuit)
        {
            [[FMShareDataBase shareDataBase] updatePersonalQueue];
            [[FMShareDataBase shareDataBase] updateCompanyQueue];
            PersonalVersion *persionVersionUpdate = [[PersonalVersion alloc] init];
            [persionVersionUpdate updateDBVersions:currentAcc.userName];
            CMessageMgr *mesMgr = [[CMessageMgr alloc] init];
            [mesMgr batchUpdateStatuWithIndeList:[mesMgr updateMessageStatuIsSendingToFailed]];
            [[CXmppMgr shareInstance] disconnect];
            [[CXmppMgr shareInstance] connect];
            
            if ([APPTOKEN isEqualToString:@"eFeng"]) {
                EFRootViewController *eFeng = [[EFRootViewController alloc] init];
                [login.navigationController pushViewController:eFeng animated:NO];
            } else if ([APPTOKEN isEqualToString:@"eTong"]){
                WZRootViewController *root = [[WZRootViewController alloc] init];
                [login.navigationController pushViewController:root animated:NO];
            } else if ([APPTOKEN isEqualToString:@"eFengAndEtong"]) {
                EFengAndEtongRootController *efengAndEtong = [[EFengAndEtongRootController alloc] init];
                [login.navigationController pushViewController:efengAndEtong animated:NO];
            } else {
                EFRootViewController *eFeng = [[EFRootViewController alloc] init];
                [login.navigationController pushViewController:eFeng animated:NO];
            }
            
        }
    }
    [self.window makeKeyAndVisible];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDelegateReachabilityChanged:) name: kReachabilityChangedNotification object: nil];
    self.hostReach = [Reachability reachabilityForInternetConnection];//可以以多种形式初始化
    
    
    [self.hostReach startNotifier];  //开始监听,会启动一个run loop
    [self appDelegateUpdateInterfaceWithReachability:self.hostReach];
    
    
    [CXmppMgr shareInstance].reachability = self.hostReach;
    
    [UMessage setLogEnabled:YES];
    
    
    [[CXmppRequestMgr shareInstance] checkVersion];
    
    
    //启动百度地图
    _mapManager = [[BMKMapManager alloc]init];
    BOOL ret = [_mapManager start:BMPKEY generalDelegate:nil];
    if (!ret) {
        NSLog(@"manager start failed!");
    }
    [FaceppAPI initWithApiKey:FACEKEY andApiSecret:FACESECRET andRegion:APIServerRegionCN];
    [FaceppAPI setDebugMode:YES];
    
    [application cancelAllLocalNotifications];
#pragma mark - 接收本地通知后启动
    [self application:application launchFinishedWithOptions:launchOptions LocalNotification:nil];
   
    if (launchOptions[@"UIApplicationLaunchOptionsShortcutItemKey"] == nil) {
        return YES;
    } else {
        return NO;
    }
}

- (void)appDelegateReachabilityChanged:(NSNotification* )note

{
    
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    
    [self appDelegateUpdateInterfaceWithReachability: curReach];
    
}

- (void)appDelegateUpdateInterfaceWithReachability: (Reachability*) curReach

{
    //对连接改变做出相应的处理动作。
    //    NetworkStatus status = [curReach currentReachabilityStatus];
    //    BOOL isForceQuit = [USER_DEFAULT boolForKey:ISFORCEQUIT];
    //    CAccountModel *currentAcc = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
    //
    //    if(status != NotReachable)
    //    {
    //        if (!isForceQuit && currentAcc != nil) {
    //            if ([CXmppMgr shareInstance].xmppStream.isDisconnected) {
    //                [[CXmppMgr shareInstance] connect];
    //            }
    //
    //        }
    //
    //    }
}


#define UMSYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define _IPHONE80_ 80000
//注册通知
-(void)registerRemoteNotification
{
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE80_
    if(UMSYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0"))
    {
        //register remoteNotification types
        UIMutableUserNotificationAction *action1 = [[UIMutableUserNotificationAction alloc] init];
        action1.identifier = @"action1_identifier";
        action1.title=@"Accept";
        action1.activationMode = UIUserNotificationActivationModeForeground;//当点击的时候启动程序
        
        UIMutableUserNotificationAction *action2 = [[UIMutableUserNotificationAction alloc] init];  //第二按钮
        action2.identifier = @"action2_identifier";
        action2.title=@"Reject";
        action2.activationMode = UIUserNotificationActivationModeBackground;//当点击的时候不启动程序，在后台处理
        action2.authenticationRequired = YES;//需要解锁才能处理，如果action.activationMode = UIUserNotificationActivationModeForeground;则这个属性被忽略；
        action2.destructive = YES;
        
        UIMutableUserNotificationCategory *categorys = [[UIMutableUserNotificationCategory alloc] init];
        categorys.identifier = @"category1";//这组动作的唯一标示
        [categorys setActions:@[action1,action2] forContext:(UIUserNotificationActionContextDefault)];
        
        UIUserNotificationSettings *userSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert
                                                                                     categories:[NSSet setWithObject:categorys]];
        [UMessage registerRemoteNotificationAndUserNotificationSettings:userSettings];
        
    } else{
        //        //register remoteNotification types
        [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
         |UIRemoteNotificationTypeSound
         |UIRemoteNotificationTypeAlert];
    }
#else
    
    //register remoteNotification types
    [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
     |UIRemoteNotificationTypeSound
     |UIRemoteNotificationTypeAlert];
    
#endif
}



-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    [UMessage setAutoAlert:NO];
    [UMessage didReceiveRemoteNotification:userInfo];
    
    //    NSLog(@"收到远程推送了");
}


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *compressDeviceToken = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
                                      stringByReplacingOccurrencesOfString: @">" withString: @""]
                                     stringByReplacingOccurrencesOfString: @" " withString: @""];
    //    NSLog(@"%@",compressDeviceToken);
    
    
    [USER_DEFAULT setObject:compressDeviceToken forKey:@"KEY_DEVICETOKEN"];
    [USER_DEFAULT synchronize];
    
    [UMessage registerDeviceToken:deviceToken];
    
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{

}



- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    
   // self.lasttime = [[UIUtil getCurrentTimeStamp] doubleValue];
    __block CAccountModel *currentAcc = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
    
    BOOL isForceQuit = [USER_DEFAULT boolForKey:ISFORCEQUIT];
    if (!isForceQuit && currentAcc != nil) {
        
        [CXmppMgr shareInstance].noticeNum = [[[CMessageMgr alloc] init] loadAllUnReadCount];
        application.applicationIconBadgeNumber = [CXmppMgr shareInstance].noticeNum;
    }
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
    
    //bug 6295 fixed by 荣则兵
    BOOL isForceQuit = [USER_DEFAULT boolForKey:ISFORCEQUIT];
    CAccountModel *currentAcc = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
    if (!isForceQuit && currentAcc != nil) {
        if (![[CXmppMgr shareInstance].xmppStream isAuthenticated]) {
            [[CXmppMgr shareInstance] connect];
        }
        
    } else {
        
    }
    
    if([USER_DEFAULT boolForKey:is_GuseturePassword] && !isForceQuit&&[[CXmppMgr shareInstance].xmppStream isAuthenticated])
    {
        GesturePasswordController *passwordVC = [[GesturePasswordController alloc] init];
        
        [self.window.rootViewController presentViewController:passwordVC animated:YES completion:nil];
    }
}


//应用程序将要退出，通常用于保存数据和一些推出前的清理工作，
- (void)applicationWillTerminate:(UIApplication *)application
{
    //    NSLog(@"应用程序将要退出");
    [[CXmppMgr shareInstance] goOffline];
    CAccountModel *currentAcc = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
    if (currentAcc != nil) {
        [[CXmppMgr shareInstance] disconnect];
    }
    
}

//当设备为应用程序分配了太多的内存，操作系统会终止应用程序的运行，在终止前会执行这个方法
//通常可以在这里进行内存清理工作，防止程序被终止
-(void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        __block NSFileManager *fileMg = [NSFileManager defaultManager];
        NSArray *array = [fileMg subpathsOfDirectoryAtPath:NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject error:nil];
        [array enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) {
            if ([fileMg fileExistsAtPath:obj]) {
                [fileMg removeItemAtPath:obj error:nil];
            }
        }];
        
    });
    
}

//当系统时间发生改变时执行
-(void)applicationSignificantTimeChange:(UIApplication *)application
{
    [[CXmppRequestMgr shareInstance] getServerTime];
}

- (void)forceQuit:(NSNotification *)notice
{
    [USER_DEFAULT setBool:YES forKey:ISFORCEQUIT];
    [USER_DEFAULT synchronize];
    
    [[CXmppMgr shareInstance] disconnect];
    [[CXmppRequestMgr shareInstance] quitLoad];
    NSString *status = [notice.object objectForKey:@"status"];
    if (status.integerValue == 1) {
        UINavigationController *rotNav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        UIViewController *vc = rotNav.childViewControllers[1];
        [rotNav popToViewController:vc animated:YES];
        
        JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:nil message:[notice.object objectForKey:@"body"]];
        [alert addButton:Button_OK withTitle:@"重新登录" handler:^(JKAlertDialogItem *item) {
            
            [[CXmppMgr shareInstance] connect];
            
        }];
        
        [alert addButton:Button_CANCEL withTitle:@"取消" handler:^(JKAlertDialogItem *item) {
            //            [[CXmppMgr shareInstance] goOffline];
            //用户退出到登录界面必须清空#pragma mark 用户退出登录以后必须清空 [CFolderMgr shareInstance].recentlyAcc = nil；
            [CFolderMgr shareInstance].recentlyAcc = nil;
            
            for (UIViewController *vc in rotNav.childViewControllers) {
                if ([vc isKindOfClass:[LoginViewController class]]) {
                    LoginViewController *login = (LoginViewController *)vc;
                    [login setverifyStatus:NO];
                    login.isUseverifyCode = NO;
                    login.errTimes = 0;
                    [login setErrStatus:NO errorMsg:nil];
                }
            }
            
            [rotNav popToRootViewControllerAnimated:NO];
        }];
        [alert show];
        
    } else {
        
        //bug 9547 fixed by lixu
        JKAlertDialog *alert2 = [[JKAlertDialog alloc]initWithTitle:nil message:[notice.object objectForKey:@"body"]];
        [alert2 addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
            
            //            [[CXmppMgr shareInstance] goOffline];
            
            //用户退出到登录界面必须清空#pragma mark 用户退出登录以后必须清空 [CFolderMgr shareInstance].recentlyAcc = nil；
            [CFolderMgr shareInstance].recentlyAcc = nil;
            UINavigationController *rotNav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
            
            for (UIViewController *vc in rotNav.childViewControllers) {
                if ([vc isKindOfClass:[LoginViewController class]]) {
                    LoginViewController *login = (LoginViewController *)vc;
                    [login setverifyStatus:NO];
                    [login setErrStatus:NO errorMsg:nil];
                    login.errTimes = 0;
                    login.isUseverifyCode = NO;
                }
            }
            
            [rotNav popToRootViewControllerAnimated:NO];
        }];
        
        [alert2 show];
        
    }
    
    
}
-(NSInteger)getCurrentDevice
{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString* code = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    NSArray *array = [code componentsSeparatedByString:@","];
    NSString *name = array.firstObject;
    NSRange range = [name rangeOfString:@"iPhone"];
    NSString *number = [name substringFromIndex:range.length];
    return number.integerValue;
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
    
    //bug 6295 fixed by 荣则兵
    BOOL isForceQuit = [USER_DEFAULT boolForKey:ISFORCEQUIT];
    CAccountModel *currentAcc = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
    
    if (!isForceQuit && currentAcc != nil) {
        [CXmppMgr shareInstance].noticeNum = [[[CMessageMgr alloc] init] loadAllUnReadCount];
        
    }
}
-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    return UIInterfaceOrientationMaskAll;
}
-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return [WXApi handleOpenURL:url delegate:[inMoneyViewController sharedInstacet]];
}
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
     return [WXApi handleOpenURL:url delegate:[inMoneyViewController sharedInstacet]];
}

#pragma mark - 接收本地通知delegate
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    [self application:application HandleBackCallWithNotification:notification];
}
- (void)configShortCutItems {
    UIApplicationShortcutIcon *iconCamera1 = [UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeLove];
      UIApplicationShortcutIcon *iconCamera2 = [UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeShare];
    NSMutableArray *shortcutItems = [NSMutableArray array];
      UIApplicationShortcutItem *item1 = [[UIApplicationShortcutItem alloc] initWithType:@"1" localizedTitle:@"打卡" localizedSubtitle:nil icon:iconCamera1 userInfo:nil];
    UIApplicationShortcutItem *item2 = [[UIApplicationShortcutItem alloc] initWithType:@"2" localizedTitle:@"发布分享" localizedSubtitle:nil icon:iconCamera2 userInfo:nil];
  
    [shortcutItems addObject:item1];
    [shortcutItems addObject:item2];
    [[UIApplication sharedApplication] setShortcutItems:shortcutItems];
}
- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler {
    switch (shortcutItem.type.integerValue) {
        case 1: {
            if ([self.window.rootViewController isKindOfClass:[UINavigationController class]]) {
                UINavigationController *nav = (UINavigationController*)self.window.rootViewController;
                WZMobileSignController *daka = [[WZMobileSignController alloc]init];
                [nav pushViewController:daka animated:YES];
            }

        }
            break;
        case 2: {
            if ([self.window.rootViewController isKindOfClass:[UINavigationController class]]) {
                UINavigationController *nav = (UINavigationController*)self.window.rootViewController;
                EFengComposeController *fenxiang = [[EFengComposeController alloc]init];
                [nav pushViewController:fenxiang animated:YES];
            }
        }   break;
        default:
            break;
    }
}
@end
